package com.leon.alishop.core.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leon.alishop.core.model.AttributesModel;
import com.leon.alishop.core.service.GoodsAttrService;
import com.leon.alishop.dao.GoodsAttrValDao;
import com.leon.alishop.model.AttrValInfo;
import com.leon.alishop.model.GoodsAttrVal;

@Service("goodsAttrService")
public class GoodsAttrServiceImpl implements GoodsAttrService{
	private static Logger log = LoggerFactory.getLogger(GoodsAttrServiceImpl.class);
	@Override
	public void insertGoodsAttrRelate(Long goodsId, List<AttributesModel> attributesList) {
		if(null == goodsId || attributesList == null){
			return;
		}
		List<GoodsAttrVal> gavList = goodsAttrValDao.selectByGoodsId(goodsId);
		Map<Integer,GoodsAttrVal> gavIdMap = new HashMap<Integer,GoodsAttrVal>();
		if(null != gavList){
			for (GoodsAttrVal _gav : gavList) {
				gavIdMap.put(_gav.getAttrValId(), _gav);
			}
		}
		GoodsAttrVal gav;
		GoodsAttrVal gavTemp;
		Set<Integer> gavIdsNew = new HashSet<Integer>();
		Integer validStatus = 0;
		for (AttributesModel am : attributesList) {
			for (AttrValInfo avi : am.getAttrValList()) {
				gavIdsNew.add(avi.getId());
				if(avi.getId()==null){
					log.error("属性值ID为空：Attributes["+am.getId()+"|"+am.getAttrName()+"AttrVal["+avi.getValueName()+"]");
					continue;
				}
				if((gavTemp = gavIdMap.get(avi.getId())) != null){
					if(!validStatus.equals(gavTemp.getStatus())){
						gav = new GoodsAttrVal();
						gav.setId(gavTemp.getId());
						gav.setStatus(0);
						goodsAttrValDao.updateByIdSelective(gav);
					}
					continue;
				}
				gav = new GoodsAttrVal();
				gav.setGoodsId(goodsId);
				gav.setAttrId(am.getId());
				gav.setAttrValId(avi.getId());
				gav.setStatus(0);
				goodsAttrValDao.insertSelective(gav);
				break;
			}
		}
		
		// 更新历史记录
		if(null != gavList){
			for (GoodsAttrVal _gav : gavList) {
				if(!gavIdsNew.contains(_gav.getAttrValId())){
					gav = new GoodsAttrVal();
					gav.setId(_gav.getId());
					gav.setStatus(1);
					goodsAttrValDao.updateByIdSelective(gav);
				}
			}
		}
	}
	
	@Autowired
	private GoodsAttrValDao goodsAttrValDao;
}
